<template>
  <view>
    <!-- 搜索框 -->
    <view class="search-box">
      <!-- 使用 uni-ui 提供的搜索组件 -->
      <uni-search-bar :focus="true" @input="input" cancelButton="none" radius="20"></uni-search-bar>
    </view>
    <!-- 搜索历史 -->
    <view class="history-container" v-if="searchResults.length === 0">
      <!-- 搜索title -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons @click="cleanHistory" type="trash" size="18"></uni-icons>
      </view>
      <!-- 历史搜索关键词 -->
      <view class="history-keywords">
        <uni-tag @click="gotoGoodsList(item)" :text="item" v-for="(item, i) in historyKeywords" :key="i"></uni-tag>
      </view>
    </view>

    <!-- 搜索列表 -->
    <view class="search-results-list" v-else>
      <view class="search-results-item" v-for="(item, i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
        <view class="search-results-item-name"> {{item.goods_name}} </view>
        <uni-icons type="arrowright"></uni-icons>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timerId: null,
        kw: '', // 收集的输入的内容
        searchResults: [], // 搜索结果 / 联想建议 / 搜索列表
        historyKeywords: []
      };
    },
    onLoad() {
      this.historyKeywords = uni.getStorageSync('kw') || []
    },
    methods: {
      input(value) {
        clearTimeout(this.timerId)
        this.timerId = setTimeout(() => {
          this.kw = value
          // 根据收集到的内容发请求
          this.getSearchResults()
        }, 500)
      },
      async getSearchResults() {
        if (!this.kw) {
          this.searchResults = []
          return false
        }
        const {
          data: res
        } = await uni.$http.get('/goods/qsearch', {
          query: this.kw
        })
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResults = res.message
        // 每次搜索完毕之后把关键词存入到 historyKeywords
        this.saveSearchHistory()
      },
      saveSearchHistory() {
        const idx = this.historyKeywords.indexOf(this.kw)
        if (idx !== -1) {
          // 找到了，干掉
          this.historyKeywords.splice(idx, 1)
        }
        this.historyKeywords.unshift(this.kw)
        // 存储到本地
        uni.setStorageSync('kw', this.historyKeywords)
      },
      cleanHistory() {
        // 清空 data 和本地的
        this.historyKeywords = []
        uni.removeStorageSync('kw')
      },
      gotoGoodsList(his) {
        // 哪些地方可以跳转到商品列表？
        // 1. 点击楼层，传递的是 query
        // 2. 点击三级分类，传递的是 cid
        // 3. 点击历史记录，传递的是 query
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + his
        })
      },
      gotoDetail(goodsId) {
        // 哪些地方可以跳转到商品详情？
        // 1. 首页的轮播图
        // 2. 搜索列表
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goodsId
        })
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    background-color: #c00000;
    position: sticky;
    top: 0;
    z-index: 9;
  }

  .search-results-list {
    padding: 0 20rpx;

    .search-results-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #efefef;
      height: 90rpx;

      .search-results-item-name {
        font-size: 24rpx;
        // 文字不允许换行（单行文本）
        white-space: nowrap;
        // 溢出部分隐藏
        overflow: hidden;
        // 文本溢出后，使用 ... 代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .history-container {
    .history-title {
      display: flex;
      height: 80rpx;
      justify-content: space-between;
      align-items: center;
      padding: 0 20rpx;
      border-bottom: 1rpx solid #efefef;
    }

    .history-keywords {
      display: flex;
      flex-wrap: wrap;

      .uni-tag {
        margin: 10rpx;
      }
    }
  }
</style>
